package com.yuxin.wx.config;

import com.yuxin.wx.annotation.HessianService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.remoting.caucho.HessianServiceExporter;
import org.springframework.stereotype.Component;

/**
 * @author zhangchuanqiang
 * @Description: 使用spring的BeanFactoryPostProcessor机制，动态暴露hessian服务
 */
@Component
public class HessianServiceScanner implements BeanFactoryPostProcessor {

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		String[] beanNames = beanFactory.getBeanNamesForAnnotation(HessianService.class);
		for (String beanName : beanNames) {
			String className = beanFactory.getBeanDefinition(beanName).getBeanClassName();
			Class<?> clasz;
			try {
				clasz = Class.forName(className);
			} catch (ClassNotFoundException e) {
				throw new BeanInitializationException(e.getMessage(), e);
			}
			String hessianServiceBeanName = "/hessian/" + beanName.replace("Impl", "");

			BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(HessianServiceExporter.class);
			builder.addPropertyReference("service", beanName);
			builder.addPropertyValue("serviceInterface", clasz.getInterfaces()[0].getName());
			((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(hessianServiceBeanName, builder.getBeanDefinition());
		}
	}
}
